#pragma once

#include "stdafx.h"
#include "NameValuePair.h"
#include "surveyAlligatorException.h"
#include "SurveyAlligatorConfig.h"



namespace SurveyAlligator {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Collections::Generic;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace Text::RegularExpressions;



	SurveyAlligatorConfig^ SurveyAlligatorConfig::instance(System::String^ filedata)
	{

		  try {
		  _instance = gcnew SurveyAlligatorConfig();
		
	    CSV_FILE_LOCATION = "";
		UNIQUENESS_KEY_ID = "";
		UNIQUENESS_ACTIVE = "";
		REPLACEMENT_POLICY = "";
		HTML_INPUT_FILE_TITLE = "";
		HTML_INPUT_FILE_CONTENTS = "";
 	    setHtmlInputFileTitle(filedata);		  	  	  
		setUniquenessProperties(filedata);
		setCsvFileLocation(filedata);
		HTML_INPUT_FILE_CONTENTS = filedata;
		
		}
		catch(surveyAlligatorException^ e)
		{
			throw gcnew surveyAlligatorException("Initializing Survey Alligator global config object failed.\n" + e->getMessage()); 
    	}
	
		return _instance;

	}


	SurveyAlligatorConfig::SurveyAlligatorConfig() 
	{ 
	
	}


	void SurveyAlligatorConfig::setHtmlInputFileTitle(System::String^ filedata)
	{
			
		if(filedata->Trim()->Length > 0)
		{
		 HTML_INPUT_FILE_TITLE = "<>";
		 System::String^ regTitle = "(<title>)(.*?)</title>";
		 System::Text::RegularExpressions::Regex^ regExpTitle = gcnew System::Text::RegularExpressions::Regex(regTitle, static_cast<System::Text::RegularExpressions::RegexOptions>(System::Text::RegularExpressions::RegexOptions::IgnoreCase));
		 System::Text::RegularExpressions::MatchCollection^ matchesTextArea = regExpTitle->Matches(filedata);
	
		 for each (System::Text::RegularExpressions::Match^ match in matchesTextArea)
		 {
			int index = match->Index;
			int length = match->Length;
			HTML_INPUT_FILE_TITLE = filedata->Substring(index,length);
		 }

		 //HTML_INPUT_FILE_TITLE = HTML_INPUT_FILE_TITLE->ToLower();
		 HTML_INPUT_FILE_TITLE = Regex::Replace(HTML_INPUT_FILE_TITLE,"<title>", "", RegexOptions::IgnoreCase);
		 HTML_INPUT_FILE_TITLE = Regex::Replace(HTML_INPUT_FILE_TITLE,"</title>", "",  RegexOptions::IgnoreCase);
		 
		 
   	 } // end of filedata length > 0
	
	} // end of method


	void SurveyAlligatorConfig::setUniquenessProperties(System::String^ filedata)
	{

    // Modification of Christian's code
	// from grammarNormalizer class
	

	String^ regExpUniqueness = "(<uniqueness)(.*?)/>";
	Regex^ rxUniqueness = gcnew Regex(regExpUniqueness, static_cast<RegexOptions>(RegexOptions::IgnoreCase));
	MatchCollection^ matchesUniqueness = rxUniqueness->Matches(filedata);
	
	if (matchesUniqueness->Count != 1){ // Occurs more than once or zero times
		surveyAlligatorException^ ex = gcnew surveyAlligatorException("The Uniqueness Tag is not valid according to the grammar specification. Please check that there is only one Uniqueness Tag");
		throw (ex);
	}

	Match^ matchUniqueness = matchesUniqueness[0];
	int indexUniqueness = matchUniqueness->Index;
	int lengthUniqueness = matchUniqueness->Length;

	System::String^ uniqTag = filedata->Substring(indexUniqueness,lengthUniqueness);
	

	String^ regExpActive = "active=\"(?<value>(yes|no))\"";
	Regex^ rxActive = gcnew Regex(regExpActive, static_cast<RegexOptions>(RegexOptions::IgnoreCase));

	if ((rxActive->Matches(uniqTag))->Count == 1)
	{
		String^ valueOfAttrActive = ((rxActive->Match(uniqTag))->Result("${value}"))->ToLower();	
		if (valueOfAttrActive->Equals("yes"))
		{
			// Its active="yes"

		    UNIQUENESS_ACTIVE = "yes";	
			
//			MessageBox::Show(UNIQUENESS_ACTIVE, "Uniqueness_Active as seen by Global COnfig",MessageBoxButtons::OK,MessageBoxIcon::Error);

			System::String^ regExpKey_id = "key_id=\"(.+?)\"";
			System::Text::RegularExpressions::Regex^ rxKey_id = gcnew Regex(regExpKey_id, static_cast<RegexOptions>(RegexOptions::IgnoreCase));
			String^ regExpRep_plcy = "rep_plcy=\"(append|replacement)\"";
			
			Regex^ rxRep_plcy = gcnew Regex(regExpRep_plcy, static_cast<RegexOptions>(RegexOptions::IgnoreCase));

			if ((rxKey_id->Matches(uniqTag))->Count == 1 && (rxRep_plcy->Matches(uniqTag))->Count == 1)
			{
				System::Collections::IEnumerator^ irx = (rxKey_id->Matches(uniqTag))->GetEnumerator();   	
				irx->MoveNext();
				Match^ match = (Match^)irx->Current;
				UNIQUENESS_KEY_ID = match->Value;
				UNIQUENESS_KEY_ID = Regex::Replace(UNIQUENESS_KEY_ID,"key_id=\"", "",  RegexOptions::IgnoreCase);
				UNIQUENESS_KEY_ID = Regex::Replace(UNIQUENESS_KEY_ID,"\"", "",  RegexOptions::IgnoreCase);

//				MessageBox::Show(UNIQUENESS_KEY_ID, "Uniqueness_Key_Id as seen by Global COnfig",MessageBoxButtons::OK,MessageBoxIcon::Error);



				irx = (rxRep_plcy->Matches(uniqTag))->GetEnumerator();
				irx->MoveNext();
				match = (Match^) irx->Current;
				REPLACEMENT_POLICY = match->Value;
				REPLACEMENT_POLICY = Regex::Replace(REPLACEMENT_POLICY,"rep_plcy=\"", "",  RegexOptions::IgnoreCase);
				REPLACEMENT_POLICY = Regex::Replace(REPLACEMENT_POLICY,"\"", "",  RegexOptions::IgnoreCase);

//				MessageBox::Show(REPLACEMENT_POLICY, "Replacement_Policy  as seen by Global COnfig",MessageBoxButtons::OK,MessageBoxIcon::Error);

				return;
			}
			else
			{
				surveyAlligatorException^ ex = gcnew surveyAlligatorException("Global Config Error: Uniqueness tag error.");
				throw (ex);
			}
		
		}else
		{ // Its active="no"
			
			UNIQUENESS_ACTIVE = "no";
			UNIQUENESS_ACTIVE = Regex::Replace(UNIQUENESS_ACTIVE, "active=\"", "",  RegexOptions::IgnoreCase);
			UNIQUENESS_ACTIVE = Regex::Replace(UNIQUENESS_ACTIVE, "\"", "",  RegexOptions::IgnoreCase);

//			MessageBox::Show(UNIQUENESS_ACTIVE, "Uniqueness_Active as seen by Global COnfig",MessageBoxButtons::OK,MessageBoxIcon::Error);
			return;
		}
	}
	else{
		surveyAlligatorException^ ex = gcnew surveyAlligatorException("Global Config Error: The Validation Tag '"+uniqTag+"' is not valid according to the grammar specification.");
		throw (ex);
	}
	surveyAlligatorException^ ex = gcnew surveyAlligatorException("Global Config Error: The Validation Tag '"+uniqTag+"' is not valid according to the grammar specification.");
	throw (ex);

	}
	

	
	void SurveyAlligatorConfig::setCsvFileLocation(System::String^ filedata)
	{  
	
	// Modification of Christian's code from
	// grammarNormalizer

	

    String^ regExpFile_info = "(<file_info)(.*?)/>";
	Regex^ rxFile_info = gcnew Regex(regExpFile_info, static_cast<RegexOptions>(RegexOptions::IgnoreCase));
	MatchCollection^ matchesFile_info = rxFile_info->Matches(filedata);
	
	if (matchesFile_info->Count != 1)
	{   // Occurs more than once or zero times
		surveyAlligatorException^ ex = gcnew surveyAlligatorException("Global Config Eror: The File_Info Tag is not valid according to the grammar specification. Please check that there is only one File_Info Tag");
		throw (ex);
	}

	Match^ matchFile_info = matchesFile_info[0];
	//String^ word = match->Groups["word"]->Value;
	int indexFile_info = matchFile_info->Index;
	int lengthFile_info = matchFile_info->Length;

	System::String^ fileLoc = filedata->Substring(indexFile_info,lengthFile_info);



	String^ regExpLocation = "location=\"(.+?)\"";
	Regex^ rxLocation = gcnew Regex(regExpLocation, static_cast<RegexOptions>(RegexOptions::IgnoreCase));

	if ((rxLocation->Matches(fileLoc))->Count == 1){
		
		System::Collections::IEnumerator^ iloc = (rxLocation->Matches(fileLoc))->GetEnumerator();
		iloc->MoveNext();
		Match^ match = (Match^)iloc->Current;
		CSV_FILE_LOCATION = match->Value;

		//MessageBox::Show(CSV_FILE_LOCATION, "CSV File Location as seen by Global Config",MessageBoxButtons::OK,MessageBoxIcon::Error);
      
		CSV_FILE_LOCATION = CSV_FILE_LOCATION->Replace("\\", "\\\\");
		CSV_FILE_LOCATION = Regex::Replace(CSV_FILE_LOCATION,"location=\"", "",  RegexOptions::IgnoreCase);
		CSV_FILE_LOCATION = Regex::Replace(CSV_FILE_LOCATION,"\"", "",  RegexOptions::IgnoreCase);	

		//MessageBox::Show(CSV_FILE_LOCATION, "CSV File Location as seen by Global Config",MessageBoxButtons::OK,MessageBoxIcon::Error);
		

		return;
	}
	else
	{
		surveyAlligatorException^ ex = gcnew surveyAlligatorException("Global Config Error: The File_Info Tag '"+fileLoc+"' is not valid according to the grammar specification.");
		throw (ex);
	}
				
}





	String^ SurveyAlligatorConfig::getHtmlInputFileTitle()
	{ return HTML_INPUT_FILE_TITLE;	}
	
	String^ SurveyAlligatorConfig::getUniquenessKeyId()
	{ return UNIQUENESS_KEY_ID;	}
	
	String^ SurveyAlligatorConfig::getUniquenessActive()
	{ return UNIQUENESS_ACTIVE; }
	
	String^ SurveyAlligatorConfig::getReplacementPolicy()
	{ return REPLACEMENT_POLICY; }

	String^ SurveyAlligatorConfig::getCsvFileLocation()
	{ return CSV_FILE_LOCATION; }


} // end of namespace